import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import { Divider, Button, DatePicker, FormInstance, Form, Dropdown, Menu } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { getBillList, stopSettle, tempSettle, saveApprovedQuantity } from '@/services/order/api';
import { PrinterOutlined, ReloadOutlined, StopOutlined } from '@ant-design/icons';
import { showMsg, MsgType, formatDate, getDateValue, isNull, isSupportSticky } from '@/utils/utils';
import FeeDetail from '@/components/OrderInfo/FeeDetail';
import { ProFormFieldSet } from '@ant-design/pro-form';
import PermissionControl from '@/components/PermissionControl';

type BillItem = {
  order_id?: string;
  bill_id?: string;
  bill_date?: string;
  brand_name?: string;
  goods_name?: string;
  goods_id?: string;
  goods_price?: number;
  specs_name?: string;
  unit?: string;
  check_num?: number;
  bill_price?: string;
  bill_status?: string;
  sett_status?: string;
}

type BillItemList = {
  record_list?: BillItem[];
  sum_record_num?: number;
  total_go_sett_price?: string;
  total_not_sent_price?: string;
  total_not_sett_price?: string;
  total_sent_price?: string;
  total_sett_price?: string;
}
interface BillInfoProps {
  order_id?: string;
  detail: any;
  reload?: () => void;
  ref?: any;
  dischargeStatus?: string;
}

const BillInfo: React.FC<BillInfoProps> = forwardRef((props, ref) => {
  const { order_id = '', reload, detail, dischargeStatus } = props;
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  const [printType, setPrintType] = useState(''); // 打印汇总/明细
  const [searchParams, setSearchParams] = useState({});

  const columns: ProColumns<BillItem>[] = [
    {
      title: '账单日期',
      dataIndex: 'bill_date',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return <ProFormFieldSet>
            <DatePicker  style={{width: '100%'}} />
            <span style={{padding: '0 5px'}}>-</span>
            <DatePicker  style={{width: '100%'}} />
          </ProFormFieldSet>
      }
    },
    {
      title: '账单日期',
      dataIndex: 'bill_date',
      search: false,
      width: 90,
      editable: false
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      search: false,
      editable: false,
      width: 110
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      editable: false,
      width: 130
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      editable: false,
      search: false,
      width: 110
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      editable: false,
      search: false,
      width: 120,
      render: (val, record) => `${val}（${record.unit}）`
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      width: 90,
      valueType: 'money',
      align: 'right',
      editable: false,
      search: false
    },
    {
      title: '核定用量',
      dataIndex: 'check_num',
      search: false,
      align: 'right',
      valueType: 'digit',
      width: 60,
      fieldProps: () => {
        return {
          min: 0,
          style: {
            width: '100%'
          }
        }
      },
      render: (dom, entity) => {
        return `${entity.check_num} ${entity.positiveFlag ? `(原${entity.bill_num})` : ''}`
      }
    },
    {
      title: '账单费用',
      dataIndex: 'bill_price',
      valueType: 'money',
      align: 'right',
      width: 90,
      editable: false,
      search: false
    },
    {
      title: '账单状态',
      dataIndex: 'bill_status',
      valueType: 'select',
      valueEnum: {
        U: '未出账',
        F: '已出账',
        D: '已删除'
      },
      editable: false,
      width: 60
    },
    {
      title: '结算状态',
      dataIndex: 'sett_status',
      valueType: 'select',
      valueEnum: {
        U: '未结算',
        W: '待结算',
        P: '已结算',
        G: '结算中'
      },
      editable: false,
      width: 60
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: 95,
      // fixed: 'right',
      // fixed: isSupportSticky() ? 'right' : '',
      render: (_, record: BillItem) => {

        if (['W', 'F'].includes(dischargeStatus as string)) {
          return '-';
        }
        // 账单状态U：未结算，P：已结算，G：结算中 W: 待结算,
        // 账单状态U：未出账，F：已出账，D：已删除 ,
        const {sett_status, bill_status} = record;
        if (sett_status === 'U' && bill_status === 'F') {
          return [
            <PermissionControl key="check" action_id="400401020">
              <a onClick={() => {
                actionRef.current?.startEditable(record.bill_id as string);
              }}>核定</a>
            </PermissionControl>
          ];
        }
        return '-';
      }
    }
  ]
  // 账单数据
  const [billData, setBillData] = useState<BillItemList>({});

  // 账单列表
  const [billList, setBillList] = useState<BillItem[]>([]);

  const [feeDetailVisible, setFeeDetailVisible] = useState<boolean>(false);

  const formRef = useRef<FormInstance>();

  const [loading, setLoading] = useState<boolean>(false);
  const [loading2, setLoading2] = useState<boolean>(false);

  // 结算
  const settle = async (type: 'temp' | 'stop') => {
    try {
      if (loading || loading2) {
        return;
      }
      if (type === 'temp') {
        setLoading(true);
        await tempSettle({order_id});
        setLoading(false);
      } else {
        setLoading2(true);
        await stopSettle({order_id});
        setLoading2(false);
      }
      showMsg(type === 'temp' ? '临时结算成功' : '计停结算成功', MsgType.SUCCESS);
      actionRef.current?.reload();
      // 结算后，重新加载项目计划列表状态，结算信息状态
      reload?.();
    } catch (error) {
      setLoading(false);
      setLoading2(false);
      showMsg(error?.data?.errmsg);
    }
  }

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    reload: () => actionRef.current?.reload(),
    clear: () => {
      formRef.current?.resetFields();
      actionRef.current?.reload();
    }
  }))

  useEffect(() => {
    // formRef.current?.setFieldsValue({
    //   bill_date: [subtractDays(30), '', currentDate()]
    // })
  }, []);
  console.log(order_id)

  useEffect(() => {
    if (order_id) {
      actionRef.current?.reload();
    }
  }, [order_id]);

  const menu = (
    <Menu onClick={(e) => {
      console.log('menu', e.key);
      setPrintType(e.key);
      setFeeDetailVisible(true);
    }}>
      <Menu.Item key="1">费用汇总</Menu.Item>
      <Menu.Item key="2">费用明细</Menu.Item>
    </Menu>
  );

  console.log('printType', printType)

  return <div className="service-record">
      <div className="header">
        <div className="title">3. 账单信息</div>
        <div className="btns fwb">
          <span>已出账单金额：
            <span style={{color: '#F5232D'}}>{billData.total_sent_price}</span>（元）
          </span>
          <span style={{paddingLeft: 15}}>未出账单金额：
            <span style={{color: '#FAAD15'}}>{billData.total_not_sent_price}</span>（元）
          </span>
          <span style={{paddingLeft: 15}}>已结算金额：
            <span style={{color: '#52C41A'}}>{billData.total_sett_price}</span>（元）
          </span>
        </div>
      </div>
      <Divider style={{margin: '10px 0 0'}} />

      <EditableProTable<BillItem, BillItem & {order_id?: string;} & COMMON.PageParams>
        rowKey="bill_id"
        bordered
        formRef={formRef}
        className="bill-pro-table"
        actionRef={actionRef}
        options={false}
        value={billList}
        onChange={setBillList}
        request={async (params) => {
          if (isNull(order_id)) {
            setBillData({
              total_sent_price: '0.00',
              total_not_sent_price: '0.00',
              total_sett_price: '0.00'
            });
            return {
              data: [],
              total: 0,
              success: true
            }
          }
          try {
            params = { ...params, order_id };
            console.log(params);
            const { bill_date } = params;
            if (bill_date) {
              params = {
                ...params, 
                ...{ begin_date: bill_date[0] && formatDate(bill_date[0], 'YYYYMMDD'), end_date: bill_date[2] && formatDate(bill_date[2], 'YYYYMMDD')}
              }

              if (bill_date[0] && bill_date[2]) {
                if (getDateValue(bill_date[0]) > getDateValue(bill_date[2])) {
                  showMsg('账单结束时间不能早于开始日期', MsgType.INFO);
                  return {
                    data: [],
                    total: 0,
                    success: true
                  };
                }
              }
              delete params['bill_date'];
            }
           
            for (const prop in params) {
              if (!params[prop]) {
                delete params[prop];
              }
            }
            setSearchParams(params);
            const data = await getBillList(params);
            setBillData(data);
            const list = data.record_list.map(item => {
              item.positiveFlag = true;
              if (item.check_num === -1) {
                item.positiveFlag = false;
                item.check_num = item.bill_num;
              }
              return {
                ...item
              }
            })
            return {
              data: list,
              total: data.sum_record_num,
              success: true
            }
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              total: 0,
              success: true
            }
          }
        }}
        editable={
          {
            form,
            type: 'single',
            editableKeys,
            onChange: setEditableRowKeys,
            onSave: async (key, row: BillItem ) => {
              try {
                const params = {
                  order_id: row.order_id,
                  bill_id: row.bill_id,
                  check_num: row.check_num
                }
                await saveApprovedQuantity(params);
                showMsg('已保存', MsgType.SUCCESS);
                actionRef.current?.reload();
              } catch (error) {
                showMsg(error?.data?.errmsg);
                actionRef.current?.reload();
                form.resetFields();
              }
            },
            actionRender: (row, config, defaultDom) => [defaultDom.save, defaultDom.cancel],
            onCancel: async () => {
              form.resetFields();
            }
          }
        }
        search={{
          span: 8,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return dom;
          }
        }}
        pagination={{
          showQuickJumper: true
        }}
        recordCreatorProps={false}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'temp',
                label: <PermissionControl action_id="400401013">
                  <Button 
                    onClick={() => {
                      settle('temp');
                    }} 
                    loading={loading}
                    disabled={!order_id || ['F'].includes(detail.plan_status) || ['W', 'F'].includes(dischargeStatus as string)}
                    icon={<StopOutlined />} 
                    type="primary">
                    临时结算
                  </Button>
                </PermissionControl>
              },
              {
                key: 'stop',
                label: <PermissionControl action_id="400401014">
                    <Button 
                      loading={loading2}
                      onClick={() => {
                        settle('stop');
                      }} 
                      disabled={!order_id || ['F'].includes(detail.plan_status) || ['W', 'F'].includes(dischargeStatus as string)}
                      icon={<StopOutlined />} 
                      type="primary">
                      计停结算
                    </Button>
                </PermissionControl>
                
              },
              {
                key: 'print',
                label: <PermissionControl action_id="400401015">
                  <Dropdown.Button type="primary" disabled={!order_id} overlay={menu}><PrinterOutlined />按条件打印</Dropdown.Button>
                </PermissionControl>
              },
              {
                key: 'refresh',
                label: <Button 
                  onClick={() => {
                    actionRef.current?.reloadAndRest?.();
                  }} 
                  icon={<ReloadOutlined />} 
                  type="primary">
                  刷新
                </Button>
              }
            ]
          }
        }}
        scroll={{
          // x: 1000
        }}
        columns={columns}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.bill_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.bill_id === clickRow ? 'tableRowClick' : ''
        }}
      />

      {
        feeDetailVisible && <FeeDetail
        searchParams={searchParams}
        type={printType}
        order_id={order_id}
        detail={detail}
        handleModalVisible={setFeeDetailVisible} />
      }
  </div>
});

export default BillInfo;